package handler

import (
	"context"
	"errors"
	"user-srv/cmd/globar"
	__ "user-srv/cmd/proto"
	"user-srv/model"
	"user-srv/until"
)

// server
type Server struct {
	__.UnimplementedUserServer
}

// 用户注册
func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	var u model.User
	u.Mobile = in.Mobile
	u.Password = until.Md5(in.Password)
	if err := u.GetOnfile(globar.DB, in.Mobile); err != nil {
		return nil, errors.New("获取数据失败")
	}
	if err := u.Create(globar.DB); err != nil {
		return nil, errors.New("添加失败")
	}

	return &__.RegisterResp{
		Id: int64(u.ID),
	}, nil
}

// 登录用户
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var u model.User
	u.Mobile = in.Mobile
	u.Password = until.Md5(in.Password)
	if err := u.Finds(globar.DB); err != nil {
		return nil, errors.New("查询失败")
	}
	if err := u.GetOnfile(globar.DB, in.Mobile); err != nil {
		return nil, errors.New("获取数据失败")
	}
	if u.Password != until.Md5(in.Password) {
		return nil, errors.New("两次密码不正确")
	}
	return &__.LoginResp{
		Id: int64(u.ID),
	}, nil
}
